package com.redis.client.controller;

import com.redis.client.bean.Account;
import com.redis.client.manage.Persistent;
import com.redis.client.util.DialogUtil;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Dialog;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author hetao
 */
public class ServerController implements Initializable {

    @FXML private TextField name;

    @FXML private TextField host;

    @FXML private TextField port;

    @FXML private TextField password;

    @FXML
    private GridPane rootLayout;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    public void init(Account account) {
        name.setText(account.getName());
        host.setText(account.getHost());
        port.setText(account.getPort().toString());
        password.setText(account.getPassword());
    }

    @FXML
    public void onTestAction() {
        System.out.println("onTestAction");


    }

    @FXML
    public void onSaveAction() {
        String nameStr=name.getText();
        String hostStr=host.getText();
        String portStr=port.getText();
        String passwordStr=password.getText();

        Persistent persistent = Persistent.getInstance();
        if(persistent.existName(nameStr)) {
            DialogUtil.showDialog("已存在（"+nameStr+"）相同的名字");
            return;
        }

        if(StringUtils.isBlank(hostStr)) {
            DialogUtil.showDialog("host不能为空");
            return;
        }

        if(StringUtils.isBlank(portStr)) {
            DialogUtil.showDialog("port不能为空");
            return;
        }
        Integer portInt=null;
        try {
            portInt = Integer.parseInt(portStr);
        } catch (Exception e) {
            DialogUtil.showDialog(portStr+"格式化失败");
            return;
        }

        Account account = new Account();
        account.setHost(hostStr);
        account.setPort(portInt);
        account.setName(nameStr);
        account.setPassword(passwordStr);
        account.setDb(0);
        persistent.addAccount(account);
        closeWindow();
    }

    @FXML
    public void onCancelAction() {
        System.out.println("onCancelAction");
        closeWindow();
    }

    private void closeWindow() {
        Stage stage = (Stage) rootLayout.getScene().getWindow();
        stage.close();
    }
}
